<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useAiApiStore } from '../stores/aiApi'

const authStore = useAuthStore()
const aiApi = useAiApiStore()
const messages = ref([])
const newMessage = ref('')
const imageFile = ref(null)
const imagePreview = ref('')
const imageBase64 = ref('')
const loading = ref(false)
const fileInput = ref(null)

const convertToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

const clearMessages = () => {
  messages.value = []
}

const handleImageUpload = async (event) => {
  const file = event.target.files[0]
  if (file) {
    try {
      imageFile.value = file
      imagePreview.value = URL.createObjectURL(file)
      imageBase64.value = await convertToBase64(file)
      clearMessages()
    } catch (error) {
      console.error('图片转换失败:', error)
    }
  }
}

const sendMessage = async () => {
  if (!(newMessage.value && imagePreview.value)) return
  if (loading.value) return
  
  loading.value = true
  try {
    // 添加用户消息到对话历史
    const userMessage = {
      type: 'user',
      content: newMessage.value,
      //image: imagePreview.value,
      image_code: imageBase64.value
    }
    messages.value.push(userMessage)
    
    // 调用AI API
    const response = await aiApi.sendRequest(messages.value)
    
    // 添加AI响应到对话历史
    messages.value.push({
      type: 'assistant',
      content: response.content
    })
    
    // 清空输入
    newMessage.value = ''
    imageFile.value = null
    //imagePreview.value = ''
    imageBase64.value = ''
    
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    loading.value = false
  }
}

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleDrop = async (event) => {
  const file = event.dataTransfer.files[0]
  if (file && file.type.startsWith('image/')) {
    try {
      imageFile.value = file
      imagePreview.value = URL.createObjectURL(file)
      imageBase64.value = await convertToBase64(file)
      clearMessages()
    } catch (error) {
      console.error('图片处理失败:', error)
    }
  }
}

const clearImage = () => {
  imageFile.value = null
  imagePreview.value = ''
  imageBase64.value = ''
}
</script>

<template>
  <div class="chat-container">
    <header class="chat-header">
      <h1>视觉推理系统</h1>
      <button class="btn-logout" @click="authStore.logout">
        <span class="icon">↪</span>
        退出登录
      </button>
    </header>
    
    <main class="chat-main">
      <!-- 图片上传区域 -->
      <div 
        class="image-upload-area"
        @drop.prevent="handleDrop"
        @dragover.prevent
        @click="triggerFileInput"
        :class="{ 'has-image': imagePreview }"
      >
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          @change="handleImageUpload"
          class="hidden"
        >
        
        <div v-if="!imagePreview" class="upload-placeholder">
          <p>点击或拖拽图片到此处上传</p>
          <br/>
          <p>注意：重新上传图片会清空对话历史</p>
        </div>
        
        <div v-else class="preview-container">
          <img :src="imagePreview" alt="预览图片">
          <button class="remove-image" @click.stop="clearImage">
            <span class="icon">✕</span>
          </button>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-section">
        <textarea
          v-model="newMessage"
          class="message-input"
          placeholder="描述您对图片的问题..."
          @keyup.enter.prevent="sendMessage"
          rows="1"
        ></textarea>
        <button 
          class="send-button"
          @click="sendMessage"
          :disabled="loading || (!(newMessage && imagePreview))"
        >
          <span class="icon">{{ loading ? '⏳' : '↗️' }}</span>
          {{ loading ? '发送中...' : '发送' }}
        </button>
      </div>

      <!-- 对话历史 -->
      <div class="messages-container">
        <div v-if="messages.length === 0" class="empty-state">
          <i class="fas fa-robot"></i>
          <h2>开始您的视觉推理对话</h2>
          <p>上传图片并提出问题，AI 将为您分析图片内容</p>
        </div>
        
        <div v-else class="message-list">
          <div v-for="(message, index) in messages" 
               :key="index"
               :class="['message', message.type]">
            <div class="avatar">
              {{ message.type === 'user' ? '👤' : '🤖' }}
            </div>
            <div class="message-content">
              <img v-if="message.image" :src="message.image" class="message-image">
              <p>{{ message.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.chat-header {
  padding: 20px 40px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  font-size: 24px;
  background: linear-gradient(135deg, #1a73e8, #8ab4f8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 600;
}

.btn-logout {
  padding: 10px 20px;
  border-radius: 8px;
  background: transparent;
  color: #1a73e8;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.btn-logout:hover {
  background: rgba(26, 115, 232, 0.1);
  cursor: pointer;
}

.chat-main {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.image-upload-area {
  width: 100%;
  height: 300px;
  border: 2px dashed #1a73e8;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.image-upload-area:hover {
  border-color: #8ab4f8;
  background: rgba(26, 115, 232, 0.05);
}

.upload-placeholder {
  text-align: center;
  color: #1a73e8;
}

.upload-placeholder i {
  font-size: 48px;
  margin-bottom: 16px;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.preview-container img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 14px;
}

.remove-image {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.input-section {
  display: flex;
  gap: 16px;
  background: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.message-input {
  flex: 1;
  border: none;
  padding: 12px;
  font-size: 16px;
  resize: none;
  border-radius: 8px;
  background: #f8f9fa;
}

.send-button {
  padding: 12px 24px;
  border-radius: 8px;
  background: #1a73e8;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.send-button:hover:not(:disabled) {
  background: #1557b0;
  cursor: pointer;
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-state {
  text-align: center;
  padding: 48px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state h2 {
  font-size: 24px;
  margin-bottom: 8px;
  color: var(--text-color);
}

.empty-state p {
  font-size: 16px;
  color: #666;
}

.message {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 20px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message.user .message-content {
  background: var(--primary-color);
  color: white;
}

.message-image {
  max-width: 300px;
  border-radius: 8px;
  margin-bottom: 8px;
}

@media (max-width: 768px) {
  .chat-header {
    padding: 16px 20px;
  }

  .chat-main {
    padding: 20px;
  }

  .image-upload-area {
    height: 200px;
  }

  .input-section {
    flex-direction: column;
  }

  .send-button {
    width: 100%;
    justify-content: center;
  }
}

/* 添加图标样式 */
.icon {
  font-size: 1.2em;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 隐藏文件输入框 */
.hidden {
  display: none !important;
  visibility: hidden;
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style> 